//
//  ST_LiveBeautyCell.swift
//  btvideo
//
//  Created by mac on 2021/3/19.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyAttributes
import HandyJSON


protocol TianCellFollowPlayProtocol {
    func padding(playView:UIView)
}

class ST_LiveBeautyCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        contentView.addSubview(shadow_view)
        shadow_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4))
        }
        
        
        root_view.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-103)
        }
        
        root_view.addSubview(talk_type_sign_view)
        talk_type_sign_view.snp.makeConstraints { (make) in
            make.height.equalTo(10)
            make.width.equalTo(80)
            make.left.equalToSuperview().offset(7)
            make.top.equalToSuperview().offset(12)
        }
        
        root_view.addSubview(onlineView)
        onlineView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
            make.width.height.equalTo(TIANCompatibleValue(value: 10))
        }
        
        
        cover_image_view.addSubview(gradient_view)
        gradient_view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
//        contentView.addSubview(action_btn)
//        action_btn.snp.makeConstraints { (make) in
//            make.right.equalToSuperview().offset(-10)
//            make.bottom.equalToSuperview().offset(-10)
//            make.height.equalTo(20)
//            make.width.equalTo(82)
//        }
        
        
        cover_image_view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(14)
        }
        
        cover_image_view.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-29)
        }
        
        
        root_view.addSubview(sign_label)
        sign_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(cover_image_view.snp.bottom).offset(10)
        }
        
        root_view.addSubview(bottom_widge_view)
        bottom_widge_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-15)
            make.height.equalTo(36)
        }
        
//        contentView.addSubview(peculiarityView)
//        peculiarityView.snp.makeConstraints { (make) in
//            make.left.equalToSuperview().offset(9)
//            make.bottom.equalToSuperview().offset(-28)
//            make.height.equalTo(20)
//        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var onlineView = ST_OnlineStatusBallControl()
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 10
          return control
      }()
    
    fileprivate lazy var shadow_view:UIImageView = {
        let control = UIImageView(image: ST_ImageUtils.imageName("room_cell_shadow"))
        control.contentMode = .scaleAspectFill
          return control
      }()
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.clipsToBounds = true
        control.contentMode = .scaleAspectFill
          return control
      }()
    
    
    fileprivate lazy var talk_type_sign_view:ST_TalkTypeSignView = {
        let control = ST_TalkTypeSignView(frame: CGRect.zero)
          return control
      }()
//    fileprivate lazy var locImageView:UIImageView = {
//        let control = UIImageView.init(image: ST_ImageUtils.imageName("LiveBeautyCellCityIcon")!)
//          return control
//      }()
//
//    fileprivate lazy var locLabel:UILabel = {
//          let control = UILabel.init()
//          control.text = ""
//        control.textColor = UIColor.white
//          control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium)
//          return control
//      }()
//
    fileprivate lazy var nickname_label:UILabel = {
          let control = UILabel.init()
          control.text = ""
        control.textColor = UIColor.white
          control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
          return control
      }()
    
    fileprivate lazy var content_label:UILabel = {
          let control = UILabel.init()
          control.text = ""
        control.textColor = .white
          control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular)
          return control
      }()
    
    fileprivate lazy var sign_label:UILabel = {
          let control = UILabel.init()
        control.numberOfLines = 0
          return control
      }()
    
//    fileprivate lazy var peculiarityView:ST_LiveBeautyPeculiarityWidgetControl = {
//          let control = ST_LiveBeautyPeculiarityWidgetControl.init()
//        control.cornerRadius = 10
//        control.borderColor = UIColor.init(white: 1, alpha: 0.5)
//        control.borderWidth = 1
//          return control
//      }()
    
//    fileprivate lazy var action_btn:UIButton = {
//
//        let control = UIButton.init(type: UIButton.ButtonType.custom)
//        control.backgroundColor = UIColor.white
//        control.cornerRadius = 20/2.0
//        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
//
//        control.setTitleColor(UIColor.init(hex: 0x333333), for: UIControl.State.normal)
//
//        control.setImage(ST_ImageUtils.imageName("LiveBeautyVoice_icon"), for: UIControl.State.normal)
//
//        control.setImage(ST_ImageUtils.imageName("LiveBeautyVideo_icon"), for: UIControl.State.selected)
//
////      control.semanticContentAttribute = .forceRightToLeft
//        control.addTarget(self, action: #selector(invite_chat_action), for: UIControl.Event.touchUpInside)
//        return control
//    }()
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        
        let control = ST_FWGradientView()
        control.bgLayer.colors = [UIColor.init(hex: 0x1F1F1F, transparency: 0)!.cgColor, UIColor.init(white: 0, alpha: 0.3).cgColor]
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        
        return control
    }()
    
    
    fileprivate lazy var bottom_widge_view:ST_RoomWidgetControl = {
        
        let control = ST_RoomWidgetControl()
        control.isUserInteractionEnabled = false
        return control
    }()
    
    
    weak var model:ST_LiveBeautyCellModel?{
        didSet{
            
            
            guard let m = model else { return  }
            
            
            if let coverUrl = self.model?.roomCover?.url,coverUrl.count > 2{
                
                self.cover_image_view.sd_setImage(with: coverUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            }else{
                self.cover_image_view.sd_setImage(with: self.model?.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            }
            
            
            
//            locLabel.text = model?.address
//
            talk_type_sign_view.isVideo = m.type == 2
            
            nickname_label.text = model?.nickname
            
//            let isVideo = m.type == 2
            
//            self.action_btn.isSelected = isVideo
            
//            var ta = "他"
//
//            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
//                ta = "她"
//            }
//
//            var str = " 与" + ta
//
//            str += ( isVideo ? "视频" : "语音")
            
//            self.action_btn.setTitleForAllStates(str)
            
            sign_label.attributedText = model?.signAttri
            
            content_label.text = m.age.string + "岁 " + m.address
            
            onlineView.status = model?.state == 3 ? 2 : 1
            
            bottom_widge_view.bind(url: m.themeImg, text: m.themeDesc)
            
//            action_btn.isHidden = m.state == 3
            
//            if let f = m.feature{
//
//                peculiarityView.isHidden = false
//
//                peculiarityView.model = f
//
//            }else{
//                peculiarityView.isHidden = true
//            }
        }
    }
}


extension ST_LiveBeautyCell:TianCellFollowPlayProtocol{
    
    func padding(playView: UIView) {
        
        root_view.insertSubview(playView, belowSubview: talk_type_sign_view)
        playView.snp.makeConstraints { make in
            make.edges.equalTo(cover_image_view)
        }
    }
    
    
    
    
}



//MARK: - Room Widget
fileprivate class ST_RoomWidgetControl:UIControl {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(smallImageView)
        smallImageView.snp.makeConstraints { (make) in
            make.top.bottom.left.equalToSuperview()
            make.width.equalTo(smallImageView.snp.height)
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(43)
            make.centerY.equalToSuperview()
        }
        self.cornerRadius = 8
        self.borderColor = UIColor(hex: 0xF0F0F0)
        self.borderWidth = 1
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var smallImageView:UIImageView = {
         let control = UIImageView()
          control.contentMode = .scaleAspectFill
        
          return control
      }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.regular)
        return control
    }()
    
    func bind(url:String,text:String) {
        
        titleLabel.text = text
        
        smallImageView.pin_setImage(from: url.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
    }
    
    
}


//MARK: - Peculiarity Widget
fileprivate class ST_LiveBeautyPeculiarityWidgetControl:UIControl {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(smallImageView)
        smallImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(14)
            make.left.equalToSuperview().offset(3)
            make.centerY.equalToSuperview()
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(22)
            make.right.equalToSuperview().offset(-7)
            make.centerY.equalToSuperview()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var smallImageView:UIImageView = {
         let control = UIImageView()
          control.contentMode = .scaleAspectFill
        control.cornerRadius = 7
          return control
      }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 9, weight: UIFont.Weight.medium)
        return control
    }()
    
    var model:ST_LiveBeautyFeature?{
        didSet{
            
            smallImageView.pin_setImage(from: model?.image.compress_small_image(width: 14).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = model?.name
            
        }
    }

}

//MARK: - Video Voice Sign View
fileprivate class ST_TalkTypeSignView:UIView{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(icon_image_view)
        icon_image_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(icon_image_view.snp.right).offset(4)
            make.centerY.equalToSuperview()
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var icon_image_view:UIImageView = {
             let control = UIImageView()
              control.contentMode = .scaleAspectFill
              return control
          }()
    
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular)
        return control
    }()
    
    var isVideo:Bool?{
        didSet{
            guard let f = isVideo else { return  }
            icon_image_view.image = UIImage(named: f ? "TalkVideoSignIcon" : "TalkVoiceSignIcon")
            titleLabel.text = f ? "视频房间" : "语音房间"
        }
    }
    
}

//MARK: - Model

class ST_LiveBeautyCellModel : NSObject{

    var accid : String
    var address : String
    var age : Int
    var avatar : String
    var birth : Int
    var channelName : String
    var cityCode : String
    var faceAuditState : Int
    var isSameCity : Bool
    var matchId : Int
    var nickname : String
    var state : Int
    var type : Int
    var vdAddress : String
    var sign : String
    var signAttri : NSAttributedString
    var themeName : String
    var themeImg : String
    var name : String
    var themeDesc : String
    var hot:Int
    var sex = ST_SEX.female
    var feature:ST_LiveBeautyFeature?
    /// 视频封面
    var roomCover:ST_TianRoomCover?
    /// 新需求主题类型==2
    var themeType:Int
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        /// RS
        
        themeType = json["theme_type"].intValue
        hot = json["hot"].intValue
        accid = json["accid"].stringValue
        sign = json["sign"].stringValue
        name = json["name"].stringValue
        themeDesc = json["theme_desc"].stringValue
        signAttri = name.withAttributes([Attribute.textColor(Color(hex: 0x999999)!),.font(Font.systemFont(ofSize: 12)),.paragraphStyle(ParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 2))])
        address = json["address"].stringValue
        age = json["age"].intValue
        avatar = json["avatar"].stringValue
        birth = json["birth"].intValue
        channelName = json["channel_name"].stringValue
        cityCode = json["city_code"].stringValue
        faceAuditState = json["face_audit_state"].intValue
        isSameCity = json["is_same_city"].boolValue
        matchId = json["match_id"].intValue
        nickname = json["nickname"].stringValue
        themeName = json["theme_name"].stringValue
        themeImg = json["image"].stringValue
        state = json["state"].intValue
        type = json["type"].intValue
        vdAddress = json["vd_address"].stringValue
        
        
        if let s = ST_SEX(rawValue: json["gender"].intValue){
            sex = s
        }
        
        
        if json["feature"]["name"].stringValue.count > 0 {
             
            feature = ST_LiveBeautyFeature.init(fromJson: json["feature"])
        }
        
        if json["room_cover"].type != .null{
            roomCover = ST_TianRoomCover(fromJson: json["room_cover"])
        }
        
        super.init()
    }
    
    init(creatRoomFromJson json: JSON) {
        themeType = json["theme_type"].intValue
        hot = json["hot"].intValue
        accid = json["accid"].stringValue
        sign = json["sign"].stringValue
        name = json["name"].stringValue
        themeDesc = json["theme_desc"].stringValue
        signAttri = name.withAttributes([Attribute.textColor(Color(hex: 0x999999)!),.font(Font.systemFont(ofSize: 12)),.paragraphStyle(ParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 2))])
        address = json["address"].stringValue
        age = json["age"].intValue
        avatar = json["avatar"].stringValue
        birth = json["birth"].intValue
        channelName = json["channel_name"].stringValue
        cityCode = json["city_code"].stringValue
        faceAuditState = json["face_audit_state"].intValue
        isSameCity = json["is_same_city"].boolValue
        matchId = json["match_id"].intValue
        nickname = json["nickname"].stringValue
        themeName = json["theme_name"].stringValue
        themeImg = json["theme_image"].stringValue
        state = json["state"].intValue
        type = json["type"].intValue
        vdAddress = json["vd_address"].stringValue
        
        sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex ?? .female
        
        if json["feature"]["name"].stringValue.count > 0 {
            feature = ST_LiveBeautyFeature.init(fromJson: json["feature"])
        }
        
        if json["room_cover"].type != .null {
            roomCover = ST_TianRoomCover(fromJson: json["room_cover"])
        }
        
        super.init()
    }

}



class ST_LiveBeautyFeature : NSObject{

    var image : String
    var name : String
    var thunbUpCount : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        
        
        image = json["image"].stringValue
        name = json["name"].stringValue
        thunbUpCount = json["thunb_up_count"].intValue
        
        super.init()
    }

}


class ST_TianRoomCover : NSObject{

    var url : String
    var videoUrl : String
    var videoDuration : Int

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        url = json["url"].stringValue
        videoUrl = json["video_url"].stringValue
        videoDuration = json["video_duration"].intValue
        
        super.init()
    }

}
